import { defineComponent, ref, onMounted, onUnmounted, computed, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ArrowLeftOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import { course as Course } from "@/api";
import { useSystemStore, useUserStore } from "@/stores";
import { getPlayId, savePlayId } from "@/utils";
import styles from "./course-play/video.module.scss";

declare const window: any;
var timer: any = null;

export default defineComponent({
  name: "CoursePlayPage",
  setup() {
    const router = useRouter();
    const route = useRoute();
    const params = route.params;
    const systemStore = useSystemStore();
    const userStore = useUserStore();

    const playUrl = ref("");
    const playDuration = ref(0);
    const playendedStatus = ref(false);
    const lastSeeValue = ref({});
    const course = ref<CourseModel | null>(null);
    const hour = ref<HourModel | null>(null);
    const loading = ref(false);
    const isLastpage = ref(false);
    const totalHours = ref<HourModel[]>([]);
    const playingTime = ref(0);
    const watchedSeconds = ref(0);
    const resourceUrl = ref<ResourceUrlModel>({});
    const myRef = ref(0);
    const playRef = ref(0);
    const watchRef = ref(0);
    const totalRef = ref(0);
    const checkPlayerStatus = ref(false);

    const systemConfig = computed(() => systemStore);
    const user = computed(() => userStore.user);

    onMounted(() => {
      timer && clearInterval(timer);
      getCourse();
      getDetail();
    });

    onUnmounted(() => {
      timer && clearInterval(timer);
    });

    watch(
      () => playDuration.value,
      (newVal) => {
        myRef.value = newVal;
      }
    );

    watch(
      () => playingTime.value,
      (newVal) => {
        playRef.value = newVal;
      }
    );

    watch(
      () => watchedSeconds.value,
      (newVal) => {
        watchRef.value = newVal;
      }
    );

    watch(
      () => hour.value?.duration,
      (newVal) => {
        totalRef.value = newVal || 0;
      }
    );

    const getCourse = () => {
      Course.detail(Number(params.courseId)).then((res: any) => {
        let totalHours: HourModel[] = [];
        if (res.data.chapters.length === 0) {
          totalHours = res.data.hours[0];
        } else if (res.data.chapters.length > 0) {
          const arr: HourModel[] = [];
          for (let key in res.data.hours) {
            res.data.hours[key].map((item: any) => {
              arr.push(item);
            });
          }
          totalHours = arr;
        }
        const index = totalHours.findIndex((i: any) => i.id === Number(params.hourId));
        if (index === totalHours.length - 1) {
          isLastpage.value = true;
        }
      });
    };

    const getDetail = () => {
      if (loading.value) {
        return true;
      }
      loading.value = true;
      Course.play(Number(params.courseId), Number(params.hourId))
        .then((res: any) => {
          console.log("API Response:", res.data);
          course.value = res.data.course;
          hour.value = res.data.hour;
          console.log("Hour data:", hour.value);
          console.log("Hour title:", res.data.hour?.title);
          document.title = res.data.hour?.title || "视频播放";
          let record: HourRecordModel = res.data.user_hour_record;
          let params = null;
          if (record && record.finished_duration && record.is_finished === 0) {
            params = {
              time: 5,
              pos: record.finished_duration,
            };
            lastSeeValue.value = params;
            lastSeeValue.value = params;
            watchedSeconds.value = record.finished_duration;
          } else if (record && record.is_finished === 1) {
            watchedSeconds.value = res.data.hour.duration;
          }
          getVideoUrl(res.data.hour.rid, params);
          loading.value = false;
        })
        .catch((e) => {
          loading.value = false;
        });
    };

    const getVideoUrl = (rid: number, data: any) => {
      Course.playUrl(Number(params.courseId), Number(params.hourId)).then((res: any) => {
        resourceUrl.value = res.data.resource_url[rid];
        playUrl.value = res.data.resource_url[rid];
        initDPlayer(res.data.resource_url[rid], 0, data);
        savePlayId(String(params.courseId) + "-" + String(params.hourId));
      });
    };

    const initDPlayer = (playUrl: string, isTrySee: number, params: any) => {
      // 添加安全检查，确保 systemConfig.value 存在
      if (!systemConfig.value) {
        console.error("系统配置未初始化，无法初始化播放器");
        return;
      }

      let banDrag = systemConfig.value?.playerIsDisabledDrag && watchRef.value < totalRef.value && watchRef.value === 0;
      window.player = new window.DPlayer({
        container: document.getElementById("meedu-player-container"),
        autoplay: false,
        video: {
          url: playUrl,
          pic: systemConfig.value.playerPoster || "",
        },
        try: isTrySee === 1,
        bulletSecret: {
          enabled: systemConfig.value.playerIsEnabledBulletSecret || false,
          text: (systemConfig.value.playerBulletSecretText || "")
            .replace("{name}", user.value?.name || "")
            .replace("{email}", user.value?.email || "")
            .replace("{idCard}", user.value?.id_card || ""),
          size: "14px",
          color: systemConfig.value.playerBulletSecretColor || "red",
          opacity: Number(systemConfig.value.playerBulletSecretOpacity || 0),
        },
        ban_drag: banDrag,
        last_see_pos: params,
      });
      // 监听播放进度更新evt
      window.player.on("timeupdate", () => {
        let currentTime = parseInt(window.player.video.currentTime);
        if (systemConfig.value?.playerIsDisabledDrag && watchRef.value < totalRef.value && currentTime - playRef.value >= 2 && currentTime > watchRef.value) {
          message.warning("首次学习禁止快进");
          window.player.seek(watchRef.value);
        } else {
          playingTime.value = currentTime;
          playTimeUpdate(parseInt(window.player.video.currentTime), false);
        }
      });
      window.player.on("ended", () => {
        if (systemConfig.value?.playerIsDisabledDrag && watchRef.value < totalRef.value && window.player.video.duration - playRef.value >= 2) {
          window.player.seek(playRef.value);
          return;
        }
        playingTime.value = 0;
        playendedStatus.value = true;
        playTimeUpdate(parseInt(window.player.video.currentTime), true);
        exitFullscreen();
        window.player && window.player.destroy();
      });
      loading.value = false;
      checkPlayer();
    };

    const playTimeUpdate = (duration: number, isEnd: boolean) => {
      if (duration - myRef.value >= 10 || isEnd === true) {
        playDuration.value = duration;
        Course.record(Number(params.courseId), Number(params.hourId), duration).then((res: any) => {});
        Course.playPing(Number(params.courseId), Number(params.hourId)).then((res: any) => {});
      }
    };

    const checkPlayer = () => {
      timer = setInterval(() => {
        let playId = getPlayId();
        if (playId && playId !== String(params.courseId) + "-" + String(params.hourId)) {
          timer && clearInterval(timer);
          window.player && window.player.destroy();
          checkPlayerStatus.value = true;
        } else {
          checkPlayerStatus.value = false;
        }
      }, 5000);
    };

    const goNextVideo = () => {
      const index = totalHours.value.findIndex((i: any) => i.id === Number(params.hourId));
      if (index === totalHours.value.length - 1) {
        isLastpage.value = true;
        message.error("已经是最后一节了！");
      } else if (index < totalHours.value.length - 1) {
        router.replace(`/course/${params.courseId}/hour/${totalHours.value[index + 1].id}`);
      }
    };

    const exitFullscreen = () => {
      let de: any;
      de = document;
      if (de.fullscreenElement !== null) {
        de.exitFullscreen();
      } else if (de.mozCancelFullScreen) {
        de.mozCancelFullScreen();
      } else if (de.webkitCancelFullScreen) {
        de.webkitCancelFullScreen();
      }
    };

    const goBack = () => {
      timer && clearInterval(timer);
      window.player && window.player.destroy();
      router.go(-1);
    };

    const goToCourse = () => {
      router.push(`/course/${params.courseId}`);
    };

    const playNext = () => {
      window.player && window.player.destroy();
      lastSeeValue.value = {};
      playendedStatus.value = false;
      goNextVideo();
    };

    return () => (
      <div class={styles["video-mask"]}>
        <div class={styles["top-cont"]}>
          <div class={styles["box"]}>
            <div class={styles["close-btn"]} onClick={goBack}>
              <ArrowLeftOutlined />
              <span class="ml-14">返回</span>
            </div>
          </div>
        </div>
        <div class={styles["video-body"]}>
          <div class={styles["video-title"]}>{typeof hour.value === "object" && hour.value !== null ? hour.value.title || "加载中..." : "加载中..."}</div>
          <div class={styles["video-box"]}>
            <div class="play-box" id="meedu-player-container" style={{ borderRadius: 8 }}></div>
            {checkPlayerStatus.value && (
              <div class={styles["alert-message"]}>
                <div class={styles["des-video"]}>您已打开新视频，暂停本视频播放</div>
              </div>
            )}
            {playendedStatus.value && (
              <div class={styles["alert-message"]}>
                {isLastpage.value && (
                  <div class={styles["alert-button"]} onClick={goToCourse}>
                    恭喜你学完最后一节
                  </div>
                )}
                {!isLastpage.value && (
                  <div class={styles["alert-button"]} onClick={playNext}>
                    播放下一节
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
      </div>
    );
  },
});
